var navdata = require("../../database/data.js");
var amapFile = require("../../database/libs/bmap-wx.min.js");
var app = getApp()
//获取应用实例
Page({
  data: {
    share_isShow: false,
    canvasClose: true,
    hiddenNames: true,
    showCenterDialog: true,
    defName: false,
    more: true,
    isShow: '',
    showLogin: true,
    screen_isShow: true,
    screen_fload_show: false,
    contShow: true,
    screen: {},
    defult: 10,
    isPage: 1,
    requestLoading: true,
    requestLoadingComplete: true, //“没有数据”的变量，默认false，隐藏  
    contNum: 10,
  },
  onPageScroll: function(e) {
    if (185 <= e.scrollTop) {
      this.setData({
        screen_fload_show: true,
      })
    } else if (185 > e.scrollTop) {
      this.setData({
        screen_fload_show: false,
        screen_isShow: true,
      })
    }


  },

  //分类详情
  onNavTo: function(event) {
    let that = this;
    wx.showLoading({
      title: "加载中",
      mask: true,
    });
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 189
      })
    }
    var scene = that.data.scene;
    var nav = event.currentTarget.dataset;
    for (var i = 0; i < that.data.nav.length; i++) {
      if (that.data.nav[i].id == nav.id) {
        that.data.nav[i] = {
          id: that.data.nav[i].id,
          name: that.data.nav[i].name,
          tool_image: that.data.nav[i].tool_image,
          changeColor: true,
        }

      } else {
        that.data.nav[i] = {
          id: that.data.nav[i].id,
          name: that.data.nav[i].name,
          tool_image: that.data.nav[i].tool_image,
        }
      }
    }
    that.setData({
      screen: nav,
      hiddenNames: true,
      defName: false,
      more: true,
      isPage: 1,
      contShow: false,
    })
    var getApiCaseCont = app.globalData.smsbaoApi + "/batch/graphql?query={case(category_id:" + nav.id + ",city:\"" + that.data.city + "\",first:3){id,name,category_id,introduction,content,case_image,}}";
    that.getApiData(getApiCaseCont, '', 'case_content', '2');
    var getApiSmsCont = app.globalData.smsbaoApi + "/batch/graphql?query={temple(category_id:" + nav.id + ",first:" + that.data.contNum + "){id,category_id,content}}";
    that.getApiData(getApiSmsCont, '', 'contents', '1');
  },

  //上滑加载
  onReachBottom: function(event) {
    if (this.data.screen.name) {
      var page = this.data.isPage + 1;
      var getApiSmsCont = app.globalData.smsbaoApi + "/batch/graphql?query={temple(category_id:" + this.data.screen.id + ",first:" + this.data.contNum + ",page:" + page + "){id,category_id,content}}";
      this.getApiData(getApiSmsCont, '', 'contents', '1', "moreData");
      wx.showNavigationBarLoading();
    } else {
      this.setData({
        requestLoadingComplete: false,
      })
    }

  },

  //电话热线
  onMakePhone: function(e) {
    wx.makePhoneCall({
      phoneNumber: '4001-021-502',
    })
  },
  //更多
  onNavMore: function(event) {
    this.setData({
      hiddenNames: !this.data.hiddenNames,
      defName: !this.data.defName,
      more: !this.data.more
    })
  },
  //筛选
  onScreenBtn: function(e) {
    if (this.data.screen != undefined && this.data.screen != '') {
      for (var i = 0; i < this.data.nav.length; i++) {
        if (this.data.nav[i].id == this.data.screen.id) {
          this.data.nav[i] = {
            id: this.data.nav[i].id,
            name: this.data.nav[i].name,
            tool_image: this.data.nav[i].tool_image,
            changeColor: true,
          }
        }
      }

    }
    this.setData({
      screen_isShow: !this.data.screen_isShow,
      nav: this.data.nav
    })
  },
  //关闭筛选
  onCloseScreen: function(e) {
    for (var i = 0; i < this.data.nav.length; i++) {
      this.data.nav[i] = {
        id: this.data.nav[i].id,
        name: this.data.nav[i].name,
        tool_image: this.data.nav[i].tool_image,
      }
    }

    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    }
    this.setData({
      requestLoading: true,
      requestLoadingComplete: true,
      nav: this.data.nav,
      screen_isShow: true,
      contShow: true,
      screen: {},
      isPage: 1,
    })
    if (this.data.screen.name == undefined || this.data.screen.name == '') {
      var getApiCaseCont = app.globalData.smsbaoApi + "/batch/graphql?query={case(city:\"" + this.data.city + "\"){id,name,category_id,introduction,content,case_image,}}";
      this.getApiData(getApiCaseCont, '', 'case_content', '2');
    }
  },
  //获取定位
  onPosition: function(e) {
    let that = this;
    that.setData({
      positionShow: true
    })
    if (that.data.city == undefined || that.data.city == '') {
      wx.getLocation({
        success: function(res) {
          var latitude = res.latitude //维度
          var longitude = res.longitude //经度        
          that.loadCity(latitude, longitude);
        },
      })
    } else {
      wx.getLocation({
        success: function(res) {
          var latitude = res.latitude //维度
          var longitude = res.longitude //经度        
          that.loadCity(latitude, longitude);
        },
      })
    }

  },
  //筛选选择
  onScreenCate: function(e) {
    var cid = e.target.id;
    for (var i = 0; i < this.data.nav.length; i++) {
      if (this.data.nav[i].id == cid) {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
          changeColor: true,
        }

      } else {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
        }
      }
    }
    this.setData({
      nav: this.data.nav
    })
  },
  //重置筛选
  onCateReset: function(e) {
    for (var i = 0; i < this.data.nav.length; i++) {
      if (this.data.nav[i].changeColor == true) {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
        }
      } else {
        this.data.nav[i] = {
          id: this.data.nav[i].id,
          name: this.data.nav[i].name,
          tool_image: this.data.nav[i].tool_image,
        }
      }
    }
    this.setData({
      nav: this.data.nav,
      contShow: true,
      screen: {},

    })
  },
  //提交筛选
  onCateSubmit: function(e) {
    for (var i = 0; i < this.data.nav.length; i++) {
      if (this.data.nav[i].changeColor == true) {
        var screen = this.data.nav[i];
        if (wx.pageScrollTo) {
          wx.pageScrollTo({
            scrollTop: 189
          })
        }
      }
    }
    if(screen){
      this.setData({
        screen: screen,
        screen_isShow: !this.data.screen_isShow,
        alert_mask_isShow: false,
        hiddenNames: true,
        defName: false,
        more: true,
        isPage: 1,
        contShow: false,
      })
      wx.showLoading({
        title: "加载中",
        mask: true,
      });
      
        var getApiCaseCont = app.globalData.smsbaoApi + "/batch/graphql?query={case(category_id:" + screen.id + ",city:\"" + this.data.city + "\",first:3){id,name,category_id,introduction,content,case_image,}}";
        this.getApiData(getApiCaseCont, '', 'case_content', '2');
        var getApiSmsCont = app.globalData.smsbaoApi + "/batch/graphql?query={temple(category_id:" + screen.id + ",first:" + this.data.contNum + "){id,category_id,content}}";
        this.getApiData(getApiSmsCont, '', 'contents', '1');
    }else{
      this.setData({
        requestLoading: true,
        requestLoadingComplete: true,
        nav: this.data.nav,
        screen_isShow: true,
        contShow: true,
        screen: {},
        isPage: 1,
      })
    }

  },

  onShareAppMessage: function() {
    return {
      title: '短信群发库 - 奇思妙想的短信内容，创意十足的短信模板',
      path: "/pages/index/index",
      success: function(res) {
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        wx.getShareInfo({
          shareTicket: shareTickets[0],
          success: function(res) {
            var encryptedData = res.encryptedData;
            var iv = res.iv;
          }
        })

      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
  loadCity: function(latitude, longitude) {
    var that = this;
    wx.request({
      url: app.globalData.mapApi + '/geocoder/v2/?ak=R4C1TODNU6HmoLhVHrG4vWPuqvvLvjE0&location=' + latitude + ',' + longitude + '&output=json&coordtype=wgs84ll',
      data: {},
      header: {
        'Content-Type': 'application/json'
      },
      success: function(res) {

        that.setData({
          city: res.data.result.addressComponent.city,
          positionShow: false,
        })
        that.getScreenData(res.data.result.addressComponent.city);
      },
    })

  },
  //获取openid
  wxlogin: function(url) {
    let that = this;
    wx.login({
      success: function(res) {
        if (res.code) {
          // //发起网络请求
          wx.request({
            url: url,
            method: "post",
            data: {
              code: res.code
            },
            success: function(res) {
              console.log(res)
              if (res.data.code == '200') {
                var openId = {
                  openId: res.data.data.openId,
                  sessionKey: res.data.data.session_key
                }
                wx.hideNavigationBarLoading();
                wx.setStorageSync('openId', openId);
              } else {
                wx.showToast({
                  title: '网络超时',
                  icon: 'loading',
                  duration: 1500
                })
              }

            }
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  //数据加载
  onLoad: function(event) {
    let that = this;
    var res = wx.getSystemInfoSync();
    that.setData({
      windowHeight: res.windowHeight
    })
    var getOpenid = app.globalData.smsbaoApi + '/batch/sapi/getOpenId';
    that.wxlogin(getOpenid);
    // scene 需要使用 decodeURIComponent 才能获取到生成二维码时传入的 scene
    var scene = decodeURIComponent(event.scene);
    console.log(scene)
    // 获取坐标
    wx.getLocation({
      type: 'gcj02', //返回可以用于wx.openLocation的经纬度
      success: function(res) {
        var latitude = res.latitude //维度
        var longitude = res.longitude //经度
        that.loadCity(latitude, longitude);
      },
      fail: function(err) {
        if (res.authSetting != '') {
          wx.getLocation({
            success: function (res) {
              var latitude = res.latitude //维度
              var longitude = res.longitude //经度        
              that.loadCity(latitude, longitude);
            },
          })
        }
      }
    });
    wx.showShareMenu({
      withShareTicket: true
    });
    //获取数据
    wx.showLoading({
      title: "加载中",
      mask: true,
    });

    var getApinavUrl = app.globalData.smsbaoApi + "/batch/sapi/get_sms_cate";
    that.getApiData(getApinavUrl, '', "nav", '0');
    var getApiSmsCont = app.globalData.smsbaoApi + "/batch/graphql?query={temple(is_top:1){id,category_id,content}}";
    that.getApiData(getApiSmsCont, '', 'select', '1');
  },

  //获取经典案例数据
  getScreenData: function(data) {
    let that = this;
    var getApiCaseCont = app.globalData.smsbaoApi + "/batch/graphql?query={case(city:\"" + data + "\"){id,name,category_id,introduction,content,case_image,}}";
    that.getApiData(getApiCaseCont, '', 'case_content', '2');
  },

  //封装请求地址函数
  getApiData: function(url, data, settedKey, sign, moreData = '') {
    let that = this
    wx.request({
      url: url,
      data: data,
      method: "post",
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        if (moreData == '') {
          var arrData = {};
          switch (sign) {
            case "0":
              arrData[settedKey] = res.data.data;
              break;
            case "1":
              arrData[settedKey] = res.data.data.temple;
              break;
            case "2":
              arrData[settedKey] = res.data.data.case;
              break;
          }
          if (arrData[settedKey] == arrData['nav']) {
            for (var i in arrData['nav']) {
              arrData['nav'][i]['tool_image'] = app.globalData.smsbaoApi + "/batch/batch/" + arrData['nav'][i].tool_image;
            }
          }
          if (arrData[settedKey] == arrData['case_content']) {
            for (var i in arrData['case_content']) {             
              arrData['case_content'][i]['case_image'] = app.globalData.smsbaoApi + "/duanxinqunfa/batch/as_case/Case/" +arrData['case_content'][i].category_id+"-"+[i]+".jpg";
            }
          }
          wx.stopPullDownRefresh();
          that.setData(arrData);
          var query = wx.createSelectorQuery();
          query.select('#index_navs_height').boundingClientRect();
          query.exec(function(res) {
            that.setData({
              navs_height: res[0].height,
            })
          })
        } else {
          if (res.data.data.temple == undefined || res.data.data.temple == '') {
            that.setData({
              requestLoadingComplete: false,
              requestLoading: true,
            })
            wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh();
            return false;
          } else {
            var updata = res.data.data.temple;
            var data = that.data.contents.concat(updata);
            that.setData({
              isPage: that.data.isPage + 1,
              contents: data,
              requestLoadingComplete: true,
              requestLoading: false
            })
          }
          wx.hideNavigationBarLoading();
          wx.stopPullDownRefresh();
        }

        setTimeout(function() {
          wx.hideLoading()
        }, 1000)
      }
    })
  },

  //跳转发送页面
  onBatchTo: function(event) {
    var data = event.currentTarget.dataset;
    wx.navigateTo({
      url: '/pages/batch/batch?data=' + JSON.stringify(data) + "&class=" + 0,
    })
  },
  //分享
  onContentShare: function(e) {
    wx.request({
      url: app.globalData.smsbaoApi + "/batch/sapi/share_create",
      data: {
        scene: "cid=" + e.currentTarget.dataset.cid + "&tid=" + e.currentTarget.dataset.tid,
        page: "pages/index/index",
        content: e.currentTarget.dataset.content,
      },
      method: "post",
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        wx.showToast({
          title: '图片生成中',
          icon: 'loading',
          duration: 2000
        })
        setTimeout(function() {
          var url = app.globalData.smsbaoApi + "/batch" + res.data;
          wx.previewImage({
            urls: [url]
          })
        }, 2000);

      }
    })

  },
})